package com.example.farmrental.controller;

import com.example.farmrental.dto.ApiResponse;
import com.example.farmrental.dto.PageResponse;
import com.example.farmrental.dto.SetmealDto;
import com.example.farmrental.entity.Setmeal;
import com.example.farmrental.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 套餐管理控制器
 */
@RestController
@RequestMapping("/api/setmeals")
@CrossOrigin(origins = "*") // 允许跨域请求
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    /**
     * 获取套餐列表（支持分页、分类筛选和关键词搜索）
     */
    @GetMapping
    public ResponseEntity<ApiResponse<PageResponse<Setmeal>>> getAllSetmeals(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword) {
        try {
            PageResponse<Setmeal> pageResponse = setmealService.getSetmealsPage(page, size, category, keyword);
            return ResponseEntity.ok(ApiResponse.success("获取套餐列表成功", pageResponse));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取套餐列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取套餐详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Setmeal>> getSetmealById(@PathVariable Long id) {
        Optional<Setmeal> setmeal = setmealService.getSetmealById(id);
        if (setmeal.isPresent()) {
            return ResponseEntity.ok(ApiResponse.success("获取套餐详情成功", setmeal.get()));
        } else {
            return ResponseEntity.ok(ApiResponse.error("套餐不存在", 404));
        }
    }

    /**
     * 新增套餐
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Setmeal>> createSetmeal(@RequestBody SetmealDto setmealDto) {
        try {
            Setmeal createdSetmeal = setmealService.createSetmeal(setmealDto);
            return ResponseEntity.ok(ApiResponse.success("新增套餐成功", createdSetmeal));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("新增套餐失败: " + e.getMessage()));
        }
    }

    /**
     * 更新套餐信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Setmeal>> updateSetmeal(@PathVariable Long id, @RequestBody SetmealDto setmealDto) {
        try {
            Optional<Setmeal> updatedSetmeal = setmealService.updateSetmeal(id, setmealDto);
            if (updatedSetmeal.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success("更新套餐成功", updatedSetmeal.get()));
            } else {
                return ResponseEntity.ok(ApiResponse.error("套餐不存在", 404));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新套餐失败: " + e.getMessage()));
        }
    }

    /**
     * 删除套餐
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteSetmeal(@PathVariable Long id) {
        try {
            if (setmealService.getSetmealById(id).isPresent()) {
                setmealService.deleteSetmeal(id);
                return ResponseEntity.ok(ApiResponse.success("删除套餐成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("套餐不存在", 404));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除套餐失败: " + e.getMessage()));
        }
    }

    /**
     * 批量删除套餐
     */
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<Void>> batchDeleteSetmeals(@RequestBody Map<String, List<Long>> payload) {
        try {
            List<Long> ids = payload.get("ids");
            if (ids != null && !ids.isEmpty()) {
                setmealService.batchDeleteSetmeals(ids);
                return ResponseEntity.ok(ApiResponse.success("批量删除套餐成功"));
            }
            return ResponseEntity.ok(ApiResponse.error("请提供要删除的套餐ID列表", 400));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量删除套餐失败: " + e.getMessage()));
        }
    }

    /**
     * 更新套餐状态 (上架/下架)
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Setmeal>> updateSetmealStatus(@PathVariable Long id, @RequestBody Map<String, String> payload) {
        try {
            String status = payload.get("status");
            if (status == null) {
                return ResponseEntity.ok(ApiResponse.error("请提供状态参数", 400));
            }
            Optional<Setmeal> updatedSetmeal = setmealService.updateSetmealStatus(id, status);
            if (updatedSetmeal.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success("更新套餐状态成功", updatedSetmeal.get()));
            } else {
                return ResponseEntity.ok(ApiResponse.error("套餐不存在", 404));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新套餐状态失败: " + e.getMessage()));
        }
    }
}